from ..models import SysConfig
from flask import jsonify
from ..base import base
from .. import db, redis_client
from sqlalchemy import text
from flask import request,current_app

# 原生sql查询
@base.route('/system/configlist', methods=['GET'])
def sysconfig_sqllist():
    raw_sql = 'SELECT config_id, config_name, config_key, config_value, config_type, create_by, \
                create_time, update_by, update_time, remark \
	           FROM sys_config'
    result = db.session.execute(text(raw_sql))
    rows = result.mappings()
    dataset = []
    for row in rows:
        ictType = SysConfig(config_id=row['config_id'], config_name=row['config_name'], 
                           config_key=row['config_key'], config_value=row['config_value'], 
                           config_type=row['config_type'], create_by=row['create_by'], 
                           create_time=row['create_time'], update_by=row['update_by'], 
                           update_time=row['update_time'], remark=row['remark'])
        dataset.append(ictType.to_json())
    current_app.logger.info("结果集数量：%d", len(dataset))
    return jsonify({'msg': '操作成功', 'code': 200, 'data': dataset})

# orm分页条件查询
@base.route('/system/configlist', methods=['POST'])
def sysconfig_list():
    filters = []
    if 'configName' in request.json:
        filters.append(SysConfig.config_name.like('%' + request.json['configName'] + '%'))
    if 'configKey' in request.json:
        filters.append(SysConfig.config_key == request.json['configKey'])
    
    page = request.args.get('pageNum', 1, type=int)
    size = request.args.get('pageSize', 10, type=int)

    pagination = SysConfig.query.filter(*filters).paginate(page=page, per_page=size, error_out=False)
    total = pagination.total
    sysConfigs = pagination.items

    dataset = []
    for sysConfig in sysConfigs:
        dataset.append(sysConfig.to_json())
    current_app.logger.info("结果集数量：%d", len(dataset))
    return jsonify({'msg': '操作成功', 'code': 200, 'data': {'total': total, 'page': page, 'size': size, 'rows': dataset}})

# orm新增数据项
@base.route('/system/addconfig', methods=['POST'])
def sysconfig_addconfig():
    sysConfig = SysConfig()

    if 'configName' in request.json:
        sysConfig.config_name = request.json['configName']
    if 'configKey' in request.json:
        sysConfig.config_key = request.json['configKey']
    if 'configValue' in request.json:
        sysConfig.config_value = request.json['configValue']
    if 'configType' in request.json:
        sysConfig.config_type = request.json['configType']
    if 'remark' in request.json:
        sysConfig.remark = request.json['remark']

    sysConfig.create_by = 'atest'

    configTobeAdd = SysConfig.query.filter_by(config_key=sysConfig.config_key).first()
    if configTobeAdd is not None:
        return jsonify({'msg': '配置项已存在', 'code': 500, 'data': ''})
    
    success = True
    try:
        db.session.add(sysConfig)
        print(sysConfig.to_json())
    except Exception as e:
        success = False
        print(e)
    finally:
        if success:
            db.session.commit()
            return jsonify({'msg': '新增成功', 'code': 200, 'data': sysConfig.to_json()})
        else:
            db.session.rollback()
            return jsonify({'msg': '新增失败', 'code': 500, 'data': ''})
        
# orm修改数据项
@base.route('/system/updateconfig', methods=['POST'])
def sysconfig_updateconfig():
    sysConfig = SysConfig()

    if 'configName' in request.json:
        sysConfig.config_name = request.json['configName']
    if 'configKey' in request.json:
        sysConfig.config_key = request.json['configKey']
    if 'configValue' in request.json:
        sysConfig.config_value = request.json['configValue']
    if 'remark' in request.json:
        sysConfig.remark = request.json['remark']

    configTobeUpdate = SysConfig.query.filter_by(config_key=sysConfig.config_key).first()
    if configTobeUpdate is None:
        return jsonify({'msg': '配置项不存在', 'code': 500, 'data': ''})
    
    success = True

    try:
        configTobeUpdate.config_name = sysConfig.config_name
        configTobeUpdate.config_value = sysConfig.config_value
        configTobeUpdate.remark = sysConfig.remark
        configTobeUpdate.update_by = 'stest'
    except Exception as e:
        success = False
        print(e)
    finally:
        if success:
            db.session.commit()
            return jsonify({'msg': '更新成功', 'code': 200, 'data': configTobeUpdate.to_json()})
        else:
            db.session.rollback()
            return jsonify({'msg': '更新失败', 'code': 500, 'data': ''})
        
# orm删除数据项
@base.route('/system/deleteconfig', methods=['POST'])
def sysconfig_deleteconfig():
    sysConfig = SysConfig()

    if 'configKey' in request.json:
        sysConfig.config_key = request.json['configKey']

    success = True

    try:
        if sysConfig.config_key is None:
            return jsonify({'msg': '请传入需要删除的配置项', 'code': 500, 'data': ''})
        else:
            SysConfig.query.filter_by(config_key=sysConfig.config_key).delete()
    except Exception as e:
        success = False
        print(e)
    finally:
        if success:
            db.session.commit()
            return jsonify({'msg': '删除成功', 'code': 200})
        else:
            db.session.rollback()
            return jsonify({'msg': '删除失败', 'code': 500, 'data': ''})
            
# redis操作
@base.route('/system/redisoperate', methods=['POST'])
def sysconfig_redisoperate():
    if 'key' in request.json:
        redis_key = request.json['key']
        current_app.logger.info("query redis key: %s",redis_key)
        redis_value = request.json['value']
        current_app.logger.info("query redis value: %s",redis_value)
        if redis_client.exists(redis_key):
            redis_value = redis_client.get(redis_key)
            current_app.logger.info("current value in redis: %s", redis_value)
            if redis_value is None or redis_value == '':
                if 'value' in request.json:
                    if redis_value is not None and redis_value!= '':
                        redis_client.set(redis_key, redis_value)
                        return jsonify({'msg': '操作成功', 'code': 200, 'data': redis_value})
                    else:
                        return jsonify({'msg': '请传入需要设置的redis值', 'code': 500, 'data': ''})
                else:
                    return jsonify({'msg': '请传入需要设置的redis值', 'code': 500, 'data': ''})
            else:
                return jsonify({'msg': '操作成功', 'code': 200, 'data': redis_value})
        else:
            redis_client.set(redis_key, redis_value)
            return jsonify({'msg': '操作成功', 'code': 200, 'data': redis_value})
    else:
        return jsonify({'msg': '请传入redis key', 'code': 500, 'data': ''})
